//
//  LGBloodPressureChart.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/3.
//  服药统计图

#import "LGMedicineRecordChart.h"
#import "LGScrollView.h"
#define topMargin    viewPix(55)

#define leftMargin   viewPix(35)+iPadMargin(10)

#define lineHeight   viewPix(20)

#define scrollWidth    (Screen_W - viewPix(83))

#define scrollHeight  (lineHeight*13+viewPix(20))

@interface LGMedicineRecordChart()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)LGEmptyView *emptyView;
/**   */
@property (nonatomic , strong)UILabel *titleLabel;
/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)UILabel *dayLabel;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)UIScrollView *medicineView;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)UIButton *takeButton;
/**   */
@property (nonatomic , strong)UIButton *stopButton;
/**   */
@property (nonatomic , strong)CAShapeLayer *shapeLayer;
/**   */
@property (nonatomic , strong)NSArray *dayArray;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
/**   */
@property (nonatomic , strong)NSMutableArray *btnArray;

@end

@implementation LGMedicineRecordChart

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return self;
}

-(void)setTitle:(NSString *)title{
    _title = title;
    self.titleLabel.text = title;
}

//药物列表
-(void)setMedicArray:(NSArray *)medicArray{
    _medicArray = medicArray;
    if(medicArray.count == 0){
        [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(70)];
    }else{
        [self.emptyView stopBufferAction];
    }
    for (UIButton *button in self.btnArray) {
        [button removeFromSuperview];
    }
    [self.btnArray removeAllObjects];
    
    CGFloat left = viewPix(8);
    CGFloat margin = viewPix(8);
    for (NSInteger i=0; i<medicArray.count; i++) {
        NSString *title = LGNSString(medicArray[i][@"name"]);
        NSString *medicineid = LGNSString(medicArray[i][@"medicine_id"]);
        CGFloat width = [title textWidthWithFont:LGFont(12) maxHeight:MAXFLOAT]+viewPix(24);
        UIButton *button = [UIButton buttonWithTitle:title titleFont:LGFont(12) normalColor:@"#999999" selectColor:@"#2E9AFC"];
        [button setBackgroundColor:[UIColor colorWithString:@"#EFEFEF"] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor colorWithString:@"#EAF4FF"] forState:UIControlStateSelected];
        button.frame = CGRectMake(left, viewPix(12), width, viewPix(28));
        button.cornerRidus = viewPix(14);
        button.selected = [medicineid isEqualToString:self.medicineid]?YES:NO;
        button.tag = 1000+i;
        [button addTarget:self action:@selector(medicButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
        [self.medicineView addSubview:button];
        [self.btnArray addObject:button];
        left += width+margin;
    }
    self.medicineView.contentSize = CGSizeMake(left+viewPix(8), viewPix(50));
}

-(void)medicButtonTouched:(UIButton *)sender{
    for (UIButton *button in self.btnArray) {
        if(button.tag == sender.tag){
            button.selected = YES;
        }else{
            button.selected = NO;
        }
    }
    NSInteger index = sender.tag-1000;
    if(self.delegate && [self.delegate respondsToSelector:@selector(requestChartData:)]){
        [self.delegate requestChartData:LGNSString(self.medicArray[index][@"medicine_id"])];
    }
}


//服药曲线
-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    self.totalCount = [dataDic[@"xaxis"] count]>0?[dataDic[@"xaxis"] count]:1;
    NSInteger count = (self.totalCount>7)?7:self.totalCount;
    self.itemWidth = scrollWidth/count;
    CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
    self.scrollView.contentSize = CGSizeMake(totalWidth, scrollHeight);
    [self.scrollView setContentOffset:CGPointMake(totalWidth-scrollWidth-viewPix(10), 0)];
    self.dayArray = dataDic[@"xaxis"];
    self.dataArray = dataDic[@"data"];
    for (NSInteger i=0; i<13; i++){
        LGDottedLineView *lineView = [self viewWithTag:4000+i];
        CGRect rect = lineView.frame;
        lineView.frame = CGRectMake(rect.origin.x, rect.origin.y, totalWidth+viewPix(30), lineHeight);
        [lineView setNeedsDisplay];
    }
}

//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    for (NSInteger i=0; i<self.dayArray.count; i++) {
        UILabel *label = [self viewWithTag:2000+i];
        [label removeFromSuperview];
    }
    _dayArray = dayArray;
    for (NSInteger i=0; i<dayArray.count; i++) {
        NSArray *tempArray = [LGNSString(dayArray[i]) componentsSeparatedByString:@"-"];
        NSString *dayString = [NSString stringWithFormat:@"%@/%@",tempArray[tempArray.count-2],tempArray[tempArray.count-1]];
        UILabel *dayLabel = [UILabel lableWithText:dayString colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, lineHeight*13, self.itemWidth, lineHeight);
        dayLabel.tag = 2000+i;
        [self.scrollView addSubview:dayLabel];
    }
}

//记录曲线
-(void)setDataArray:(NSArray *)dataArray{
    for (NSInteger i=0; i<self.dataArray.count; i++) {
        UIButton *button = [self viewWithTag:3000+i];
        [button removeFromSuperview];
    }
    
    if(_shapeLayer){
        [self.shapeLayer removeFromSuperlayer];
    }
    
    _dataArray = dataArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<dataArray.count; i++) {
        CGFloat value = [dataArray[i][@"value"] floatValue];
        CGFloat pointY = scrollHeight-(value/0.5*lineHeight+viewPix(20)+lineHeight*0.5);
        if(value>0){
            NSLog(@">>???>>%f--%f",value,pointY);
        }
        UIButton *button = [UIButton buttonWithImage:@"服药-服药" selectImage:@"服药-停药"];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.selected = ([dataArray[i][@"isdrug"] integerValue]>0)?YES:NO;
        button.tag = 3000+i;
        [self.scrollView addSubview:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#429BFF"];
}

//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count < 2) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 1.0;
    self.shapeLayer = shapeLayer;
    [self.scrollView.layer addSublayer:shapeLayer];
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:3000+i];
        [self.scrollView bringSubviewToFront:button];
    }
}



-(void)createSubView{
    [self addSubview:self.titleLabel];
    [self addSubview:self.baseView];
    [self.baseView addSubview:self.medicineView];
    [self.baseView addSubview:self.dayLabel];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.unitLabel];
    [self.baseView addSubview:self.takeButton];
    [self.baseView addSubview:self.stopButton];
    NSArray *titleArray = @[@"6.0",@"5.5",@"5",@"4.5",@"4",@"3.5",@"3",@"2.5",@"2",@"1.5",@"1.0",@"0.5",@"0.0"];
    for (NSInteger i=0; i<titleArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:titleArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        [self.baseView addSubview:label];
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(20), lineHeight)];
        lineView.tag = 4000+i;
        [self.scrollView addSubview:lineView];
    }
    [self.baseView addSubview:self.emptyView];
}

-(NSMutableArray *)btnArray{
    if(!_btnArray){
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

-(LGEmptyView *)emptyView{
    if(!_emptyView){
        _emptyView = [[LGEmptyView alloc] initWithFrame:CGRectMake(0, 0, Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(35))];
        _emptyView.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
        _emptyView.userInteractionEnabled = NO;
        _emptyView.hidden = YES;
    }
    return _emptyView;
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"患者自己" colorString:@"#333333" textFont:LGFontWeight(15, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(viewPix(20), viewPix(7), viewPix(100), viewPix(23));
    }
    return _titleLabel;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [UIView shadowViewWithColor:@"#B2BDC7" offset:CGSizeMake(0, 2) opacity:0.15 radius:7];
        _baseView.frame = CGRectMake(viewPix(16), kMaxY(self.titleLabel.frame)+viewPix(12), Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(35));
        _baseView.backgroundColor = [UIColor whiteColor];
        _baseView.cornerRidus = 15;
    }
    return _baseView;
}

-(UIScrollView *)medicineView{
    if(!_medicineView){
        _medicineView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Screen_W-viewPix(32), viewPix(50))];
        _medicineView.showsHorizontalScrollIndicator = NO;
    }
    return _medicineView;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
    }
    return _scrollView;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@" " colorString:@"#666666" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _unitLabel.frame = CGRectMake(3, topMargin-6, 50, viewPix(17));
    }
    return _unitLabel;
}


-(UIButton *)takeButton{
    if(!_takeButton){
        _takeButton = [UIButton buttonWithTitle:@"  服药记录" titleFont:LGFont(15) textColor:@"#333333" imageName:@"服药-服药记录"];
        _takeButton.frame = CGRectMake((Screen_W-viewPix(32))/2.0-viewPix(122)-iPadMargin(50)-viewPix(20), kMaxY(self.scrollView.frame), viewPix(122)+iPadMargin(50), viewPix(20));
        _takeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    }
    return _takeButton;
}

-(UIButton *)stopButton{
    if(!_stopButton){
        CGFloat margin = (Screen_W-viewPix(64)-viewPix(122)*2-viewPix(45)-iPadMargin(50)*3)/2.0;
        _stopButton = [UIButton buttonWithTitle:@"  停药记录" titleFont:LGFont(15) textColor:@"#333333" imageName:@"服药-停药记录"];
        _stopButton.frame = CGRectMake(kMaxX(self.takeButton.frame)+viewPix(40), kMinY(self.takeButton.frame), viewPix(122)+iPadMargin(50), viewPix(20));
        _stopButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    }
    return _stopButton;
}



@end
